/****************************************************
          File Name:internet_domain-2.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Fri 03 Oct 2014 02:41:41 PM CST
*****************************************************/

#include"net.h"

int main(int argc, char *argv[])
{
    if(argc<2 || strcmp(argv[1],"--help")==0)
    {
        printf("%s ipv4addr\nor\n%s any",argv[0],argv[0]);
        exit(1);
    }
    
    int sfd, bytes;
    struct sockaddr_in addr;
    char *buf;
    int ipaddr;
    buf=malloc(SIZE);

    if(inet_pton(AF_INET,argv[1],&ipaddr)==-1)
        err("get ip addr");

    sfd=socket(AF_INET,SOCK_STREAM,0);
    if(sfd==-1)
        err("socket");
    memset(&addr,0,sizeof(struct sockaddr_in));
    addr.sin_family=AF_INET;
    addr.sin_port=htons(8888);
    addr.sin_addr.s_addr=strcmp(argv[1],"any")==0?INADDR_ANY:ipaddr;
    if(connect(sfd,(struct sockaddr *)&addr,sizeof(struct sockaddr_in))==-1)
        err("connect");
    while((bytes=read(STDIN_FILENO,buf,SIZE))>0)
        if(write(sfd,buf,bytes)!=bytes)
            err("write");
    if(bytes==-1)
        err("read");
    close(sfd);
	free(buf);
    exit(0);
}
